package com.yt.fras.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yt.fras.pojo.base.JsonResult;
import com.yt.fras.pojo.base.LoginUser;
import com.yt.fras.pojo.entity.Attendance;
import com.yt.fras.pojo.entity.AttendanceUser;
import com.yt.fras.service.AttendanceService;
import com.yt.fras.service.AttendanceUserService;
import com.yt.fras.service.FaceServer;
import com.yt.fras.utils.ResultTool;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Optional;

import static com.yt.fras.constant.AttendanceStatus.ATTENDANCE;

/**
 * ClassName:FaceController
 * Package:com.yt.fras.controller
 * Description:
 * 人脸识别模块
 *
 * @date:2021/11/4 22:08
 * @author:yt
 */
@RestController
@Api(tags = "人脸识别模块")
@RequestMapping("/fras")
public class FaceController {

    @Autowired
    private FaceServer faceServer;

    @Autowired
    private AttendanceUserService attendanceUserService;

    @Autowired
    private AttendanceService attendanceService;


    /**
     * 人脸识别
     *
     * @param image
     * @return
     */
    @PostMapping("/user/faceRecognition")
    @ApiOperation(value = "人脸识别")
    @ApiResponses({
            @ApiResponse(code = 0, message = "未检测到人脸！"),
            @ApiResponse(code = 0, message = "不是本人！"),
            @ApiResponse(code = 200, message = "人脸识别成功！"),
            @ApiResponse(code = 500, message = "系统出现错误~")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "attendanceId", value = "用户Id", required = true),
            @ApiImplicitParam(paramType = "body", name = "image", value = "图片base64编码", required = true)
    })
    public String faceRecognition(@RequestParam String image, @RequestParam String attendanceId) {
        JsonResult result;
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (attendanceService.getById(attendanceId) == null) {
            result = ResultTool.fail();
            result.setMsg("考勤记录不存在！");
            return JSON.toJSONString(result);
        }
        if (faceServer.faceCheck(image)) {
            String searchId = faceServer.faceSearch(image);
            //判断人脸识别返回的userId是否和当前登录的用户Id相同
            if (Optional.ofNullable(searchId).filter(s -> s.equals(loginUser.getId())).isPresent()) {
                Attendance attendance = attendanceService.getById(attendanceId);
                QueryWrapper<AttendanceUser> wrapper = new QueryWrapper<>();
                wrapper.eq("attendance_id", attendanceId)
                        .eq("user_id", loginUser.getId());
                AttendanceUser attendanceUser = attendanceUserService.getOne(wrapper);
                if (attendanceUser == null) {
                    attendanceUser = new AttendanceUser();
                    attendanceUser.setAttendanceId(attendanceId);
                    attendanceUser.setUserId(loginUser.getId());
                    attendanceUser.setAttendanceTime(new Date());
                    attendanceUser.setStatus(ATTENDANCE);
                    attendance.setActualCount(attendance.getActualCount() + 1);
                    attendance.setTotalCount(attendance.getTotalCount() + 1);
                    if (attendanceUserService.save(attendanceUser) && attendanceService.updateById(attendance)) {
                        result = ResultTool.success();
                        result.setMsg("考勤成功！");
                    } else {
                        result = ResultTool.fail();
                        result.setMsg("考勤失败！");
                    }
                } else {
                    attendanceUser.setStatus(ATTENDANCE);
                    attendanceUser.setAttendanceTime(new Date());
                    attendance.setActualCount(attendance.getActualCount() + 1);
                    if (attendanceUserService.updateById(attendanceUser) && attendanceService.updateById(attendance)) {
                        result = ResultTool.success();
                        result.setMsg("考勤成功！");
                    } else {
                        result = ResultTool.fail();
                        result.setMsg("考勤失败！");
                    }
                }

            } else {
                result = ResultTool.fail();
                result.setMsg("不是本人！");
            }
        } else {
            result = ResultTool.fail();
            result.setMsg("未检测到人脸！");
        }

        return JSON.toJSONString(result);
    }

}
